<template>
  <div class="page-emr-treatment-action-plan" id="emrTreatmentActionPlan">
    <div class="action-plan-header">
      <h3 style="margin: 0">哮喘行动计划</h3>
    </div>
    <treatmentActionPlanHeader
      v-model="patientInfo"
      followDate="followDate"
    ></treatmentActionPlanHeader>
    <div class="content-wrapper">
      <!-- 控制良好 -->
      <div class="action-plan-good">
        <el-table
          border
          size="medium"
          :data="[
            { rowOne: 1, rowTwo: 2 },
            { rowOne: 1, rowTwo: 2 },
          ]"
          :span-method="arraySpanMethod"
        >
          <!-- <div slot="header"></div> -->
          <el-table-column width="320px">
            <template v-slot="{ $index }">
              <div v-if="$index == 0">
                <div class="flex-control actin-left-header">
                  <h1>哮喘控制良好</h1>
                  <div class="icon-to-right" style="color: #009541">
                    <svg-icon
                      class-name="ccaap_right_arrow-icon"
                      icon-class="ccaap_right_arrow"
                    />
                  </div>
                </div>
                <div class="action-left">
                  <img src="@/assets/imgs/control-good.jpg" alt="" />
                  <div>
                    <ul>
                      <li>呼吸通畅</li>
                      <li>没有咳嗽或喘息</li>
                      <li>夜间睡眠安稳</li>
                      <li>能够正常学习、运动、玩耍</li>
                    </ul>
                    <div>峰流速实测值 ≧ 80%预计值</div>
                  </div>
                </div>
              </div>
              <div v-else class="action-plan-content-wrapper">
                <div class="request-methods textarea-content">
                  <div v-for="(item, index) in actionGreen" :key="index">
                    {{ item }}
                  </div>
                </div>
                <div
                  v-if="actionPlanValue !== '简易版'"
                  class="request-methods"
                >
                  <div class="flex-control">
                    <i class="el-icon-warning"></i>
                    <div>
                      如果运动引起哮喘，可在运动前30分钟选择以下药物（如果运动引起哮喘，请及时就医）：
                    </div>
                  </div>
                  <div>
                    <div class="emergency-medicine-select textarea-content">
                      <div v-for="(item, index) in usageGreen" :key="index">
                        {{ item }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column min-width="320px">
            <template v-slot="{ $index }">
              <div v-if="$index == '0'" class="header-desc">
                请坚持每日使用控制药物
                <span>（C-Controller）</span>
                ，预防哮喘发作
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 先兆 -->
      <div class="action-plan-aggravate-signs">
        <el-table
          border
          size="medium"
          :data="[
            { rowOne: 1, rowTwo: 2 },
            { rowOne: 1, rowTwo: 2 },
          ]"
          :span-method="arraySpanMethod"
        >
          <!-- <div slot="header"></div> -->
          <el-table-column width="320px">
            <template v-slot="{ $index }">
              <div v-if="$index == 0">
                <div class="flex-control actin-left-header">
                  <h1>哮喘加重先兆</h1>
                  <div class="icon-to-right" style="color: #ba6539">
                    <svg-icon
                      class-name="ccaap_right_arrow-icon"
                      icon-class="ccaap_right_arrow"
                    />
                  </div>
                </div>
                <div class="action-left">
                  <img src="@/assets/imgs/control-bad.jpg" alt="" />
                  <div>
                    <ul>
                      <li>频繁咳嗽</li>
                      <li>喘息</li>
                      <li>胸闷</li>
                      <li>夜间咳嗽加重</li>
                    </ul>
                    <div>峰流速实测值60%~80%预计值之间：__</div>
                  </div>
                </div>
              </div>

              <div v-else class="action-plan-content-wrapper">
                <div class="request-methods">
                  <div v-if="actionPlanValue !== '简易版'">规律治疗方案:</div>
                  <div
                    v-if="actionPlanValue !== '简易版'"
                    class="textarea-content"
                  >
                    <div v-for="(item, index) in actionYellow" :key="index">
                      {{ item }}
                    </div>
                  </div>
                  <div>恶化时按需使用药物:</div>
                  <div class="textarea-content">
                    <div v-for="(item, index) in usageYellow" :key="index">
                      {{ item }}
                    </div>
                  </div>
                </div>
                <div class="request-emergency">
                  <div class="flex-control">
                    <i class="el-icon-warning"></i>
                    <div key="lowerThanSix" v-if="patientAge === 'lessThan'">
                      <div>出现一下症状请前往急诊就诊:</div>
                      <div>
                        ·按需使用缓解药物，如病情需要可间隔二十分钟使用一次，连用三次症状无明显改善;
                      </div>
                      <div>·启动缓解药物治疗两小时内，大于6吸未得到改善；</div>
                      <div>·24小时内病情未得到缓解;</div>
                      <div>·急性呼吸窘迫。</div>
                    </div>

                    <div key="higherThanSix" v-else>
                      <div>出现以下症状请前往急诊就诊:</div>
                      <div>
                        ·按需使用缓解药物，如病情需要可间隔二十分钟使用一次，连用三次症状无明显改善;
                      </div>
                      <div>·峰流速仍低于个人最佳值(或正常预计值)60%;</div>
                      <div>·48小时内病情未得到缓解。</div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column min-width="320px">
            <template v-slot="{ $index }">
              <div v-if="$index == '0'" class="header-desc">
                立即使用以下缓解药物
                <span>（R-Reliever）</span>
                ，并升级每日控制药物
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 紧急 -->
      <div class="action-plan-acute-attack">
        <el-table
          size="medium"
          border
          :data="[
            { rowOne: 1, rowTwo: 2 },
            { rowOne: 1, rowTwo: 2 },
          ]"
          :span-method="arraySpanMethod"
        >
          <!-- <div slot="header"></div> -->
          <el-table-column width="320px">
            <template v-slot="{ $index }">
              <div v-if="$index == 0">
                <div class="flex-control actin-left-header">
                  <h1>哮喘急性发作</h1>
                  <div class="icon-to-right" style="color: #dd272e">
                    <svg-icon
                      class-name="ccaap_right_arrow-icon"
                      icon-class="ccaap_right_arrow"
                    />
                    <!-- <span></span>
                    <span></span>
                    <span></span>
                    <span></span>
                    <div></div> -->
                  </div>
                </div>
                <div class="action-left">
                  <img src="@/assets/imgs/control-worse.jpg" alt="" />
                  <div>
                    <ul>
                      <li>剧烈咳嗽、憋气、呼吸困难</li>
                      <li>走路、说话困难，无法平卧</li>
                      <li>鼻翼扇动，口唇、指甲青紫</li>
                      <li>焦虑、烦燥不安、意识模糊</li>
                    </ul>
                    <div>峰流速实测值 &lg; 60%预计值：__</div>
                  </div>
                </div>
              </div>
              <div v-else class="action-plan-content-wrapper">
                <div class="request-methods">
                  <div v-if="actionPlanValue !== '简易版'">规律治疗方案:</div>
                  <div
                    v-if="actionPlanValue !== '简易版'"
                    class="textarea-content"
                  >
                    <div v-for="(item, index) in actionRed" :key="index">
                      {{ item }}
                    </div>
                  </div>
                  <div>恶化时按需使用药物:</div>
                  <div class="textarea-content">
                    <div v-for="(item, index) in usageRed" :key="index">
                      {{ item }}
                    </div>
                  </div>
                </div>
                <div class="request-emergency">
                  <div class="flex-control">
                    <i class="el-icon-warning"></i>
                    <span>情况紧急，立即就医</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="320px">
            <template v-slot="{ $index }">
              <div v-if="$index == '0'" class="header-desc">
                哮喘急性发作，请立即使用以下药物，并立即就医或拨打急救电话
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="action-plan-acute-cnUse" v-if="isCn">
        <div>中医使用药物:</div>
        <div class="textarea-content textarea-content-cnUse">
          <div v-for="(item, index) in cnUse" :key="index">{{ item }}</div>
        </div>
      </div>
    </div>
  </div>
  <div class="footer-div">
    <debounce-btn
      class="footer-button"
      :disabled="disabled"
      type="primary"
      @debounce="toSubmit(2)"
    >
      提交并发送行动计划
    </debounce-btn>

    <debounce-btn
      class="footer-button"
      type="primary"
      @debounce="getHtml2Img()"
    >
      打印
    </debounce-btn>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { nextTick } from 'vue'
  import treatmentActionPlanHeader from './treatmentActionPlanHeader'
  // eslint-disable-next-line max-len
  import html2Img from '@/components/PrintTemplateDialog/PrescriptionTemplate/html2Img.vue'
  import { load, save, withdrawActionPlan } from '@/api/modules/actionPlan'
  import common from '@/utils/common'
  import emrHook from '@/hooks/emr.vue'
  import * as moment from 'moment'
  export default {
    name: 'emrTreatmentActionPlan',
    data() {
      return {
        disabled: false,
        isSubmit: false,
        actionYellow: [],
        usageYellow: [],
        usageRed: [],
        actionRed: [],
        usageGreen: [],
        emergencyUse: [],
        actionGreen: [],
        cnUse: [],
        actionPlanValue: '简易版',
        treatmentPlan: '',
        addTreatmentPlan: null,
        desensitizationTreatment: null,

        emergencyRelieverMedicine: {
          checked: [],
          salbutamolQuantity: '',
          budesonideSpec: '',
          budesonideQuantity: '',
        },
        categoryDrugList: [],
        categoryDrugData: null,
        query: null,
        showEmrDoctorID: null,
        actionDatas: [],
        followDate: null,
        createTime: null,
        isCn: false,
      }
    },
    computed: {
      ...mapGetters(['patientInfo']),
      patientAge() {
        console.log(
          'this.patientInfo.ageType =' +
            JSON.stringify(this.$store.getters.patientInfo.ageType)
        )
        return this.$store.getters.patientInfo.ageType
      },
      patientInfo() {
        const startTime = moment(new Date().getTime()).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        return {
          ...this.$store.getters.patientInfo,
          orgName: this.$store.getters.userInfo.orgName,
          startTime: this.createTime || startTime,
          followDate: this.followDate,
        }
      },
    },
    components: { treatmentActionPlanHeader },
    mounted() {
      this.toLoad()
    },
    methods: {
      downloadFile(content, fileName) {
        //下载base64图片
        var base64ToBlob = function (code) {
          let parts = code.split(';base64,')
          let contentType = parts[0].split(':')[1]
          let raw = window.atob(parts[1])
          let rawLength = raw.length
          let uInt8Array = new Uint8Array(rawLength)
          for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i)
          }
          return new Blob([uInt8Array], {
            type: contentType,
          })
        }
        let aLink = document.createElement('a')
        let blob = base64ToBlob(content) //new Blob([content]);
        let evt = document.createEvent('HTMLEvents')
        evt.initEvent('click', true, true)
        aLink.download = fileName
        aLink.href = URL.createObjectURL(blob)
        aLink.click()
      },
      async withdraw(item) {
        await common.syncAlert('确定撤回已提交的病历？病历修改需谨慎操作？')
        common.XmLoading(true)
        withdrawActionPlan({ medicalRecordId: this.$route.query.emrId })
          .then(async () => {
            common.XmLoading(false)
            common.XmMessage(0, '撤回成功！')
            // Todo 刷新页面
            this.toLoad()
            // 刷新状态栏
            this.$store.dispatch('patient/loadEmrStatus', {
              medicalRecordId: this.$route.query.emrId,
              patientId: this.$route.query.id,
            })
          })
          .catch(() => {
            common.XmLoading(false)
          })
      },
      async toSubmit(status) {
        if (this.isSubmit) {
          this.withdraw(status)
        } else {
          this.toSave(status)
        }
      },
      async toSave(status) {
        let errorMsg = ''
        if (!this.$route.query.emrId) errorMsg = '需要先提交病历'
        if (!errorMsg) {
          let isNotData = true
          Object.keys(this.actionDatas).forEach((key) => {
            const item = this.actionDatas[key]
            if (item.length > 0) {
              isNotData = false
            }
          })
          if (isNotData)
            errorMsg = '发送行动计划，需要在治疗方案中至少添加一组药物'
        }
        if (errorMsg) {
          common.XmMessage(3, errorMsg)
          return
        }
        // const actionDatas = {
        //   actionYellow: this.actionYellow,
        //   usageYellow: this.usageYellow,
        //   usageRed: this.usageRed,
        //   actionRed: this.actionRed,
        //   usageGreen: this.usageGreen,
        //   emergencyUse: this.emergencyUse,
        //   actionGreen: this.actionGreen,
        // }
        await common.syncAlert(
          status === 2
            ? '该行动计划将发送给患者，【治疗方案】和【行动计划】将不能修改'
            : null
        )
        const data = {
          actionPlanType: this.actionPlanValue,
          content: this.actionDatas,
          medicalRecordId: this.$route.query.emrId,
          patientId: this.$route.query.id,
          status,
          treatmentPlan: this.treatmentPlan,
          addTreatmentPlan: this.addTreatmentPlan,
          desensitizationTreatment: this.desensitizationTreatment,
          followDate: this.followDate,
        }
        common.XmLoading(true)
        await save(data)
          .then((res) => {
            common.XmLoading()
            if (status === 2) {
              this.disabled = true
            }
            common.XmMessage(0, res.message)
            this.$store.dispatch('patient/loadEmrStatus', {
              medicalRecordId: this.$route.query.emrId,
              patientId: this.$route.query.id,
            })
            this.toLoad()
          })
          .catch(() => {
            common.XmLoading()
          })
      },
      toLoad() {
        // console.log('emrId =' + this.$route.query.emrId)
        load({
          medicalRecordId: this.$route.query.emrId,
          actionPlanType: '简易版',
        })
          .then((res) => {
            const { dto, followDate, tcm } = res.data
            this.followDate = followDate

            this.isCn = tcm ? true : false
            if (dto) {
              this.actionPlanValue = dto.actionPlanType
              this.treatmentPlan = dto.treatmentPlan
              this.desensitizationTreatment = dto.desensitizationTreatment
              this.addTreatmentPlan = dto.addTreatmentPlan
              this.isSubmit = dto.status === 2 ? true : false
              this.createTime = dto.createTime
              if (dto.status === 2) {
                this.disabled = true
              }
              if (dto.content) {
                this.actionDatas = dto.content
                this.initData(dto.content)
              }
            }
          })
          .catch((err) => {})
      },
      initData({
        actionYellow = [],
        usageYellow = [],
        usageRed = [],
        actionRed = [],
        usageGreen = [],
        actionGreen = [],
        emergencyUse = [],
        cnUse = [],
      }) {
        function convert(items) {
          const { findTermChs } = emrHook()
          return items.map((item) => {
            return `${item.commonName}(${item.spec}) 每次${
              item.singleDosage
            } ${findTermChs(item.frequency)} ${item.usage}\n`
          })
        }
        this.actionYellow = convert(actionYellow)
        this.usageYellow = convert(usageYellow)
        this.usageRed = convert(usageRed)
        this.actionRed = convert(actionRed)
        this.usageGreen = convert(usageGreen)
        this.actionGreen = convert(actionGreen)
        this.emergencyUse = convert(emergencyUse)
        this.cnUse = convert(cnUse)
      },
      async getHtml2Img() {
        const { htmlToImg } = html2Img()
        await nextTick()
        const svgElements = document.body.querySelectorAll('svg')
        svgElements.forEach((item) => {
          item.setAttribute(
            'width',
            item.getBoundingClientRect().width.toString()
          )
        })
        htmlToImg('emrTreatmentActionPlan', (base64) => {
          console.log('base64 =' + base64)
          this.downloadFile(base64, 'ccaap')
        })
      },
      arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0 && columnIndex === 0) {
          return {
            rowspan: 2,
            colspan: 1,
          }
        } else {
          return {
            rowspan: 1,
            colspan: 1,
          }
        }
      },
    },
  }
</script>
<style scoped lang="scss">
  .page-emr-treatment-action-plan {
    padding: 12px;
    overflow: auto;

    .textarea-content {
      min-height: 100px;
      border: 0;
      margin: 0;
      // background-color: #f2f2f2;
      padding: 6px;
      border: 1px;
      background-color: var(--el-disabled-bg-color);
      border-color: var(--el-disabled-border-color);
      color: var(--el-disabled-text-color);
      cursor: not-allowed;
    }
    .textarea-content-cnUse {
      margin-top: 10px;
      min-height: 60px;
    }
    // border-left: 1px solid #eee;
    .ccaap_right_arrow-icon {
      font-size: 70px;
      vertical-align: middle;
    }
    .flex-control {
      display: flex;
      align-items: center;
    }

    .actin-left-header {
      padding-left: 12px;
    }

    .action-left {
      display: flex;
      align-items: flex-start;
      padding: 10px;

      img {
        width: auto;
        height: 120px;
      }

      ul {
        padding-left: 24px;
        margin-top: 0;

        li {
          list-style: disc;
        }
      }
    }

    .icon-to-right {
      font-size: 0;
      line-height: 0;
      color: inherit;
      margin-left: 36px;

      span {
        display: inline-block;
        vertical-align: middle;
        background-color: currentColor;
        margin: 0 3px;
        height: 34px;
        border-radius: 2px;
        overflow: hidden;
      }

      span:first-child {
        width: 6px;
      }

      span:nth-child(2) {
        width: 12px;
      }

      span:nth-child(3) {
        width: 18px;
      }

      span:nth-child(4) {
        width: 24px;
      }

      div:nth-child(5) {
        width: 21px;
        height: 21px;
        border-right: 0.001px none white;
        border-bottom: 21px solid #fff;
        border-left: 21px solid currentColor;
        border-top: 21px solid #fff;
      }
    }

    .action-plan-header {
      display: flex;
      align-items: center;

      h3 {
        font-size: 18px;
      }

      .acton-plan-date {
        margin-left: 12px;
        display: flex;
        align-items: center;

        .vdp-datepicker {
          margin-left: 12px;
        }
      }
    }

    .emergency-medicine-select {
      .el-checkbox {
        padding: 0;
      }
    }

    .content-wrapper .el-table .has-gutter {
      display: none;
    }

    .content-wrapper .el-table--medium td {
      padding: 0;
      vertical-align: top;
    }

    .content-wrapper .el-table thead {
      display: none;
    }

    :deep(.el-table--enable-row-hover) {
      .el-table__body tr:hover > td {
        background-color: #fff !important;
      }
    }

    .action-plan-good,
    .action-plan-aggravate-signs,
    .action-plan-acute-attack {
      margin: 12px 0;
    }

    .action-plan-good {
      color: #009541;

      .el-table {
        color: inherit;
      }
    }

    .action-plan-aggravate-signs {
      color: #ba6539;

      .el-table {
        color: inherit;
      }
    }

    .action-plan-acute-attack {
      color: #dd272e;

      .el-table {
        color: inherit;
      }
    }

    .el-icon-warning {
      margin-right: 6px;
    }

    .action-plan-content-wrapper {
      padding: 10px;
    }

    .el-table .cell,
    .el-table--border td:first-child .cell,
    .el-table--border th:first-child .cell {
      padding: 0;
    }

    .request-methods {
      .el-textarea {
        textarea {
          border: 0;
          margin: 0;
          padding: 0;
          background-color: #f2f2f2;
          padding: 6px;
        }
      }
    }

    .control-upgrade-title {
      margin: 6px 0;
    }

    .request-emergency {
      line-height: 24px;
      margin: 12px 6px;

      .flex-control {
        align-items: flex-start;

        .el-icon-warning {
          line-height: 24px;
        }
      }
    }

    .header-desc {
      margin: 10px 6px;
    }
  }

  @media screen and (max-width: 1200px) {
    .mobile {
      #emrTreatmentActionPlan {
        margin-left: 0;
      }
    }
  }

  .footer-div {
    margin-top: 10px;
    .el-button {
      float: right;
      margin-right: 12px;
      margin-left: 0px;
    }
  }
  .action-plan-acute-cnUse {
    margin-top: 22px;
    font-size: 14px;
  }
</style>
